package com.common.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.StarAppConst;
import com.common.allCommon.CommUtil;
import com.common.android.ui.LocalAlbum.FileInfo;
import com.common.android.ui.LocalAlbum.ImageSearchService;
import com.common.android.ui.LocalAlbum.LocalImageController;
import com.common.android.ui.LocalAlbum.SortedMediaFiles;
import com.common.android.utils.DisplayUtil;
import com.common.android.utils.ToastUtils;
import com.common.android.utils.task.progressTask.ProgressTask;
import com.common.utils.StarAppUtils;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.product.android.ui.widget.NestInListGridView;
import com.starappallcommon.R;

/**
 * 明星App，浏览本地相册图片共通界面
 * 
 * <br>
 * Created 2014-5-5 下午2:37:20
 * 
 * @version
 * @author HuangYK
 * 
 * @see
 */
// 这个类是之前LSJ实现的，现在从共通包内搬过来，具体优化暂时不做处理
public class StarAppLocalAlbumMultiSelect extends StarAppBaseFramentActivity
		implements OnItemClickListener, OnClickListener, Observer {
	
	/**
	 * 已经选择的文件路径。
	 */
	public static final String CAMEAR_FILE="CAMEAR_FILE";
	
	/**
	 * 已经选择的文件路径。
	 */
	public static final String SELECTED_IMG="SELECTED_IMG";

	private static final String TAG = "StarAppLocalAlbumMultiSelect";

	/** 图片路径 */
	public static final String IMAGE_PATHS = "imagePaths";
	/** 是否是多选 */
	public static final String IS_MULTI_SELECT = "IS_MULTI_SELECT";
	/** 是否是使用GIF */
	public static final String IS_USED_GIF = "IS_USED_GIF";

	/** 最多选取9张 */
	private static final int MAX_SELECT_COUNT = 9;
	/** 最近照片显示两排，共8张图片 */
	private static final int MAX_RECENT_COUNT = 8; //
	/** 44:图片40dip,maring4dip */
	private static final int FOOT_COLUMN_WIDTH = 44;

	/** 顶部Title */
	private CommonActivityTitle mCommonActivityTitle;

	/** 相册目录列表 */
	private ListView mLvLocalAlbum;
	/** 相册目录列表适配器 */
	private AlbumListAdapter m_alAdapter;
	/** 相册目录列表数据 */
	private ArrayList<SortedMediaFiles> mListAlbum;

	/** ListView 的HeaderView */
	private LinearLayout mLlHead;
	/** 顶部数据拍照按钮以及相册中最新的七张图片列表 */
	private GridView mGridViewRecent;
	/** 顶部数据适配器 */
	private HeadGridViewAdapter mHeadGridViewAdapter;
	/** 顶部数据 */
	private ArrayList<FileInfo> mListRecent;

	/** 相册目录中的照片数据列表 */
	private GridView mGvSelectMore;
	/** 相册目录中的照片数据列表适配器 */
	private SelectMoreGridViewAdapter mSelectMoreGridViewAdapter;
	/** 相册目录中的照片数据列表数据 */
	private ArrayList<FileInfo> mListSelectMore;

	/** 底部多选区域 */
	private RelativeLayout mRlBottom;
	/** 底部已选择图片列表 */
	private NestInListGridView mGvBottom;
	/** 底部已选择图片列表适配器 */
	private FootGridViewAdapter mFootGridViewAdatper;
	/** 底部已选择图片列表数据 */
	private ArrayList<FileInfo> mlistSelectedFile;

	/** 底部确认按钮 */
	private Button mBtnFinish;

	/** 屏幕宽度 */
	private int mScreenWidth;

	/** 照片URI */
	private Uri mPhotoUri = null;
	/** 相册文件 */
	private File mCameraFile = null;

	/** 存放适配器中的View */
	private Map<Integer, View> mMapRecent;
	/** 存放适配器中的View */
	private Map<Integer, View> mMapSelectMore;

	/** 更新UI */
	private ExecutorService mUpdateUI = Executors.newSingleThreadExecutor();

	/** 搜索系统相片的服务 */
	private Intent mIntentService = null;

	/** 相册列表数据 */
	private HashMap<String, SortedMediaFiles> mMapAlbumList;

	/** 是否是多选，true表示多选，false表示单选 */
	private boolean mIsMultiSelect = false;
	
	/**是否使用GIF图片*/
	private boolean mIsUsedGif = false;

	/** 用于ImageLoader，防止OOM的option */
	public DisplayImageOptions mAvoidOOMOptions = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.local_image_default)
			.showImageForEmptyUri(R.drawable.local_image_default)
			.showImageOnFail(R.drawable.local_image_default)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.imageScaleType(ImageScaleType.EXACTLY).resetViewBeforeLoading()
			.build();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		restoreInstanceState(savedInstanceState);
		setContentView(R.layout.startapp_local_album_multi_select);
		getIntentData();
		initView();
		initData();
		initEvent();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(CAMEAR_FILE, mCameraFile);
	}

	/**
	 * 界面恢复
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:52
	 * 
	 * @param savedInstanceState
	 *            保存的数据
	 * @author : HuangYK
	 */
	private void restoreInstanceState(Bundle savedInstanceState) {
		if (null != savedInstanceState) {
			mListAlbum = savedInstanceState
					.getParcelableArrayList("LIST_ALBUM");
			
			mCameraFile = (File) savedInstanceState.getSerializable(CAMEAR_FILE);
			if (mCameraFile != null && mCameraFile.exists()) {
				doCameraResult();
			}
		}
	}

	/**
	 * 获取intent中的数据
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:41
	 * 
	 * @author : HuangYK
	 */
	private void getIntentData() {
		Intent intent = getIntent();
		ArrayList<String> listImages = intent
				.getStringArrayListExtra(IMAGE_PATHS);
		mlistSelectedFile = new ArrayList<FileInfo>();
		// 构造几个FileInfo以显示在底部
		if (null != listImages && !listImages.isEmpty()) {
			for (String strImagePaht : listImages) {
				FileInfo info = new FileInfo();
				info.mFilePathOrName = strImagePaht;
				mlistSelectedFile.add(info);
			}
		}
		mIsMultiSelect = intent.getBooleanExtra(IS_MULTI_SELECT, false);
		
		mIsUsedGif = intent.getBooleanExtra(IS_USED_GIF, false);

		mMapRecent = new HashMap<Integer, View>();
		mMapSelectMore = new HashMap<Integer, View>();
		mMapAlbumList = new HashMap<String, SortedMediaFiles>();

	}

	/**
	 * 初始化视图
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:35
	 * 
	 * @author : HuangYK
	 */
	private void initView() {
		mScreenWidth =  StarAppUtils.getInstance().readDisplayMetrics().x ;

		mCommonActivityTitle = (CommonActivityTitle) findViewById(R.id.common_title);
		mLvLocalAlbum = (ListView) findViewById(R.id.lvLocalAlbum);
		initHeaderView();
		initSelectMore();
		initBottom();
		initTypeface();
	}

	/**
	 * 设置字体
	 * 
	 * <br>
	 * Created 2014-8-13 下午10:59:47
	 * 
	 * @author : HuangYK
	 */
	private void initTypeface() {
		mCommonActivityTitle.setTitleTextTypeface(StarAppConst.getInstance()
				.getLTXTypeface(), true);
		StarAppUtils.setViewTypeFace(mBtnFinish, true);
	}

	/**
	 * 初始化ListView headerview
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:31
	 * 
	 * @author : HuangYK
	 */
	private void initHeaderView() {
		// 列表头部
		mHeadGridViewAdapter = new HeadGridViewAdapter();
		mListRecent = new ArrayList<FileInfo>();
		mLlHead = (LinearLayout) View.inflate(this,
				R.layout.local_album_recent_grid, null);
		mGridViewRecent = (GridView) mLlHead.findViewById(R.id.grid_recent);
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mGridViewRecent
				.getLayoutParams();
		final int offset = 5;
		linearParams.height = mScreenWidth / 2 + offset;
		mGridViewRecent.setLayoutParams(linearParams);
	}

	/**
	 * 初始化底部视图
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:26
	 * 
	 * @author : HuangYK
	 */
	private void initBottom() {
		mRlBottom = (RelativeLayout) findViewById(R.id.rlBottom);
		// 如果多选则显示底部，单选则隐藏
		if (mIsMultiSelect) {
			mRlBottom.setVisibility(View.VISIBLE);
		} else {
			mRlBottom.setVisibility(View.GONE);
		}
		mFootGridViewAdatper = new FootGridViewAdapter();
		mGvBottom = (NestInListGridView) findViewById(R.id.gvBottom);
		mBtnFinish = (Button) this.findViewById(R.id.btnFinish);
	}

	/**
	 * 初始化选择更多列表
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:21
	 * 
	 * @author : HuangYK
	 */
	private void initSelectMore() {
		// 文件夹中选择更多
		mGvSelectMore = (GridView) findViewById(R.id.gvSelectMore);
		mSelectMoreGridViewAdapter = new SelectMoreGridViewAdapter();
		mListSelectMore = new ArrayList<FileInfo>();
	}

	/**
	 * 初始化视图操作事件监听
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:16
	 * 
	 * @author : HuangYK
	 */
	@Override
	protected void initEvent() {
		mCommonActivityTitle.setTitleBtnCallback(mTitleBtnCallback);
		mBtnFinish.setOnClickListener(this);
		mLvLocalAlbum.setOnItemClickListener(this);
		mGridViewRecent.setOnItemClickListener(this);
		mGvBottom.setOnItemClickListener(this);
		mGvSelectMore.setOnItemClickListener(this);
	}

	/**
	 * 初始化数据
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:17:10
	 * 
	 * @author : HuangYK
	 */
	private void initData() {

		mGridViewRecent.setAdapter(mHeadGridViewAdapter);

		mLvLocalAlbum.addHeaderView(mLlHead);
		m_alAdapter = new AlbumListAdapter(this);
		mLvLocalAlbum.setAdapter(m_alAdapter);
		mLvLocalAlbum.setOnScrollListener(scrollListener);

		mGvSelectMore.setAdapter(mSelectMoreGridViewAdapter);
		mGvSelectMore.setOnScrollListener(scrollListener);
		mGvBottom.setAdapter(mFootGridViewAdatper);

		setGvBottomWidth();
		setFinishBtnText();
	}

	/**
	 * 获取最新的照片列表数据
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:16:53
	 * 
	 * @param list
	 *            最新照片列表数据
	 * @author : HuangYK
	 */
	private void getRecentList(List<SortedMediaFiles> list) {
		if (null == list || list.isEmpty()) {
			return;
		}

		mListRecent.clear();
		mListRecent.add(new FileInfo()); // 第一个按钮为拍照，增加一个空值
		for (SortedMediaFiles smf : list) {
			if (null != smf) {
				List<FileInfo> listFI = smf.getFilesList();
				if (null != listFI) {
					for (FileInfo fi : listFI) {
						mListRecent.add(fi);
						if (MAX_RECENT_COUNT == mListRecent.size()) {
							mHeadGridViewAdapter.initSelectState();
							return;
						}
					}
				}
			}
		}
		mHeadGridViewAdapter.initSelectState();
	}

	/**
	 * 更新UI
	 * 
	 * @n<b>函数名称</b> :updateUI
	 * @brief
	 * @see
	 * @version Ver 1.1
	 * @param
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-4-16下午5:29:12
	 */
	private void updateUI() {
		mUpdateUI.submit(new Runnable() {
			@Override
			public void run() {
				final ArrayList<SortedMediaFiles> list = LocalImageController
						.getInstance().getMediaFilesByCameraFirst();
				getRecentList(list);

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (null != list) {
							mListAlbum = list;
						}

						mHeadGridViewAdapter.notifyDataSetChanged();
						m_alAdapter.notifyDataSetChanged();
					}
				});
			}
		});
	}

	@Override
	public void update(Observable observable, Object data) {
		updateUI();
	}

	@Override
	public void onResume() {
		if (View.VISIBLE == mLvLocalAlbum.getVisibility()) {
			LocalImageController.getInstance().addObserver(this);
		}

		super.onResume();
	}

	@Override
	public void onPause() {
		LocalImageController.getInstance().delObserver(this);
		super.onPause();
	}

	/**
	 * 更新底部
	 * 
	 * <br>
	 * Created 2014-6-9 下午6:05:25
	 * 
	 * @author : HuangYK
	 */
	private void UpdateFoot() {
		setFinishBtnText();
		setGvBottomWidth();
		mFootGridViewAdatper.notifyDataSetChanged();
	}

	/**
	 * 设置完成按钮文字
	 * 
	 * <br>
	 * Created 2014-6-9 下午6:05:33
	 * 
	 * @author : HuangYK
	 */
	public void setFinishBtnText() {
		if (mlistSelectedFile.isEmpty()) {
			mBtnFinish.setText(getString(R.string.confirm_selection));
			mBtnFinish.setBackgroundResource(R.drawable.btn_confirm_unable);
			mBtnFinish.setEnabled(false);
		} else {
			mBtnFinish.setText(getString(R.string.confirm_selection) + " ("
					+ mlistSelectedFile.size() + "/" + MAX_SELECT_COUNT + ")");
			mBtnFinish.setBackgroundResource(R.drawable.common_tip_dlg_pink_rbtn);
			mBtnFinish.setEnabled(true);
		}
	}

	/**
	 * 设置底部宽度
	 * 
	 * <br>
	 * Created 2014-6-9 下午6:05:45
	 * 
	 * @author : HuangYK
	 */
	public void setGvBottomWidth() {
		ViewGroup.LayoutParams layoutParams = null;
		int width = (DisplayUtil.dip2px(this, FOOT_COLUMN_WIDTH))
				* (mFootGridViewAdatper.getCount() + 1);
		mGvBottom.setNumColumns(mFootGridViewAdatper.getCount() + 1);
		if (mGvBottom.getLayoutParams() != null) {
			layoutParams = mGvBottom.getLayoutParams();
			layoutParams.width = width;
		} else {
			layoutParams = new ViewGroup.LayoutParams(width,
					LayoutParams.WRAP_CONTENT);
		}
		mGvBottom.setLayoutParams(layoutParams);
		mGvBottom.setSelection(mFootGridViewAdatper.getCount() - 1);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btnFinish) {
			doMultiSelectFinish();
		}
	}

	/**
	 * 多选状态的结束
	 * 
	 * @n<b>函数名称</b> :doMultiSelectFinish
	 * @brief
	 * @see
	 * @version Ver 1.1
	 * @param
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-4-17下午6:07:05
	 */
	private void doMultiSelectFinish() {
		ArrayList<String> listSelectedImg = new ArrayList<String>();
		for (FileInfo info : mlistSelectedFile) {
			listSelectedImg.add(info.mFilePathOrName);
		}

		Intent intent = new Intent();
		intent.putStringArrayListExtra(SELECTED_IMG, listSelectedImg);
		setResult(RESULT_OK, intent);
		finish();
	}

	/**
	 * 单选状态的结束
	 * 
	 * <br>
	 * Created 2014-6-6 下午5:32:21
	 * 
	 * @param path
	 *            路径
	 * @author : HuangYK
	 */
	private void doSingSelectFinish(String path) {
		Intent intent = new Intent();
		Uri uri = Uri.parse(path);
		intent.setData(uri);
		setResult(RESULT_OK, intent);
		finish();
	}

	/**
	 * 
	 * 
	 * <br>
	 * Created 2014-6-9 下午6:06:36
	 * 
	 * @version StarAppLocalAlbumMultiSelect
	 * @author HuangYK
	 * 
	 * @see
	 */
	class HeadGridViewAdapter extends BaseAdapter {
		private boolean[] mSelectState;

		/**
		 * 初始化选中状态
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:16:32
		 * 
		 * @author : HuangYK
		 */
		public void initSelectState() {
			if (null == mListRecent) {
				return;
			}

			int iSize = mListRecent.size();
			mSelectState = new boolean[iSize];

			for (int iIndex = 0; iIndex < mListRecent.size(); iIndex++) {
				for (FileInfo info : mlistSelectedFile) {
					if (info.mFilePathOrName.equalsIgnoreCase(mListRecent
							.get(iIndex).mFilePathOrName)) {
						mSelectState[iIndex] = true;
						break;
					}
				}
			}
		}

		/**
		 * 设置选中
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:16:19
		 * 
		 * @param position
		 *            位置
		 * @author : HuangYK
		 */
		public void setSelect(int position) {
			if (null == mSelectState || position < 1
					|| position + 1 > mSelectState.length) {
				return;
			}

			if (MAX_SELECT_COUNT == mlistSelectedFile.size()
					&& !mSelectState[position]) {
				// 已经有9张并尝试再选
				ToastUtils.display(StarAppLocalAlbumMultiSelect.this,
						R.string.tweet_upload_images_limit);
				return;
			}

			File fImage = new File(mListRecent.get(position).mFilePathOrName);
			if (!fImage.exists()) {
				Toast.makeText(StarAppLocalAlbumMultiSelect.this,
						R.string.pic_is_deleted, Toast.LENGTH_SHORT).show();
				return;
			}

			mSelectState[position] = !mSelectState[position];

			Holder holder = (Holder) (mMapRecent.get(position)).getTag();
			if (null != holder) {
				if (mSelectState[position]) {
					mlistSelectedFile.add(mListRecent.get(position));
					holder.ivMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
				} else {
					removeSeletedImg(mListRecent.get(position).mFilePathOrName);
					holder.ivMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
				}
			}
			UpdateFoot();
		}

		@Override
		public int getCount() {
			if (null == mListRecent) {
				return 1;
			}
			return mListRecent.size();
		}

		@Override
		public Object getItem(int position) {
			if (mListRecent != null && position < mListRecent.size()) {
				return mListRecent.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * item
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:16:08
		 * 
		 * @version StarAppLocalAlbumMultiSelect.HeadGridViewAdapter
		 * @author HuangYK
		 * 
		 * @see
		 */
		class Holder {
			ImageView ivRecentItem;
			ImageView ivMask;
			ImageView ivClicked;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView != null && 0 != position) {
				holder = (Holder) convertView.getTag();
				// mMapRecent.remove(position);
			} else {
				LayoutInflater inflate = LayoutInflater
						.from(StarAppLocalAlbumMultiSelect.this);
				convertView = inflate
						.inflate(R.layout.local_album_recent, null);
				holder = new Holder();
				holder.ivRecentItem = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.ivMask = (ImageView) convertView
						.findViewById(R.id.iv_selected_mask);
				holder.ivClicked = (ImageView) convertView
						.findViewById(R.id.iv_clicked_to_select);
				convertView.setTag(holder);
			}

			if (0 == position) {
				// 第一个显示拍照按钮
				holder.ivRecentItem
						.setBackgroundResource(R.drawable.take_photo);

			} else if (position < mListRecent.size()) {
				// 加载其他图片
				ImageLoader.getInstance().displayImage(
						CommUtil.LOCAL_FILE_PREFIX
								+ mListRecent.get(position).mFilePathOrName,
						holder.ivRecentItem, mAvoidOOMOptions, null);
			}

			if (null != mSelectState && position > 0
					&& mSelectState.length > position) {
				if (mSelectState[position]) {
					holder.ivMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
				} else {
					holder.ivMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
				}
			}

			mMapRecent.put(position, convertView);

			return convertView;
		}
	}

	/**
	 * 相册列表适配器
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:15:49
	 * 
	 * @version StarAppLocalAlbumMultiSelect
	 * @author HuangYK
	 * 
	 * @see
	 */
	public class AlbumListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private boolean mbDisplay = true;

		/**
		 * 
		 * Creates a new instance of AlbumListAdapter. <br>
		 * Created 2014-5-5 下午3:15:59
		 * 
		 * @param context
		 *            上下文
		 */
		public AlbumListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		/**
		 * 设置是否显示
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:15:36
		 * 
		 * @param bDispaly
		 *            true：显示，false：不显示
		 * @author : HuangYK
		 */
		public void setDisplay(boolean bDispaly) {
			mbDisplay = bDispaly;
		}

		@Override
		public int getCount() {
			if (null == mListAlbum) {
				return 0;
			}
			return mListAlbum.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		/**
		 * item
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:15:26
		 * 
		 * @version StarAppLocalAlbumMultiSelect.AlbumListAdapter
		 * @author HuangYK
		 * 
		 * @see
		 */
		public final class ViewHolder {
			public ImageView ivDemo;
			public TextView tvDirName;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater
						.inflate(R.layout.local_album_item, null);
				holder.ivDemo = (ImageView) convertView
						.findViewById(R.id.iv_demo);
				holder.tvDirName = (TextView) convertView
						.findViewById(R.id.tv_dir_name);

				StarAppUtils.setViewTypeFace(holder.tvDirName, false);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (null != mListAlbum && position < mListAlbum.size()) {
				SortedMediaFiles smf = mListAlbum.get(position);
				if (null != smf) {
					// 取出第一张显示
					FileInfo info = smf.getFirstFile();
					if (null != info) {
						holder.ivDemo.setBackgroundResource(0);
						if (mbDisplay) {
							ImageLoader.getInstance().displayImage(
									CommUtil.LOCAL_FILE_PREFIX
											+ info.mFilePathOrName,
									holder.ivDemo, mAvoidOOMOptions, null);
						} else {
							holder.ivDemo.setImageBitmap(BitmapFactory
									.decodeResource(getResources(),
											R.drawable.local_image_default));
						}

					}

					holder.tvDirName.setText(smf.getDirName() + "("
							+ smf.getFilesCount() + ")");
				}
			}

			return convertView;
		}
	}

	/**
	 * 进入更多选择界面
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:14:57
	 * 
	 * @version StarAppLocalAlbumMultiSelect
	 * @author HuangYK
	 * 
	 * @see
	 */
	class SelectMoreGridViewAdapter extends BaseAdapter {
		private boolean[] mSelectState;
		private boolean mbDisplay = true;

		/**
		 * 初始化选中状态
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:15:09
		 * 
		 * @author : HuangYK
		 */
		public void initSelectState() {
			if (null == mListSelectMore) {
				return;
			}

			int iSize = mListSelectMore.size();
			mSelectState = new boolean[iSize];

			for (int iIndex = 0; iIndex < mListSelectMore.size(); iIndex++) {
				for (FileInfo info : mlistSelectedFile) {
					if (info.mFilePathOrName.equalsIgnoreCase(mListSelectMore
							.get(iIndex).mFilePathOrName)) {
						mSelectState[iIndex] = true;
						break;
					}
				}
			}
		}

		/**
		 * 设置是否显示
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:14:39
		 * 
		 * @param bDispaly
		 *            true：显示，false：不显示
		 * @author : HuangYK
		 */
		public void setDisplay(boolean bDispaly) {
			mbDisplay = bDispaly;
		}

		@Override
		public int getCount() {
			if (null == mListSelectMore) {
				return 0;
			}
			return mListSelectMore.size();
		}

		@Override
		public Object getItem(int position) {
			if (mListSelectMore != null && position < mListSelectMore.size()) {
				return mListSelectMore.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * item
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:14:26
		 * 
		 * @version StarAppLocalAlbumMultiSelect.SelectMoreGridViewAdapter
		 * @author HuangYK
		 * 
		 * @see
		 */
		class Holder {
			ImageView ivMoreItems;
			ImageView ivSelectedMask;
			ImageView ivClicked;
		}

		/**
		 * 设置选中
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:14:15
		 * 
		 * @param position
		 *            位置
		 * @author : HuangYK
		 */
		public void setSelect(int position) {
			if (null == mSelectState || position < 0
					|| position > mSelectState.length) {
				return;
			}

			if (MAX_SELECT_COUNT == mlistSelectedFile.size()
					&& !mSelectState[position]) {
				// 已经有9张并尝试再选
				ToastUtils.display(StarAppLocalAlbumMultiSelect.this,
						R.string.tweet_upload_images_limit);
				return;
			}

			String strPath = mListSelectMore.get(position).mFilePathOrName;
			File fImage = new File(strPath);
			if (!fImage.exists()) {
				Toast.makeText(StarAppLocalAlbumMultiSelect.this,
						R.string.pic_is_deleted, Toast.LENGTH_SHORT).show();
				return;
			}

			mSelectState[position] = !mSelectState[position];

			Holder holder = null;
			if (0 == position) {
				// pos为0不准确，这里直接从gridview取元素
				holder = (Holder) mGvSelectMore.getChildAt(0).getTag();
			} else {
				holder = (Holder) (mMapSelectMore.get(position)).getTag();
			}

			if (null != holder) {
				if (mSelectState[position]) {
					mlistSelectedFile.add(mListSelectMore.get(position));
					holder.ivSelectedMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
				} else {
					removeSeletedImg(mListSelectMore.get(position).mFilePathOrName);
					holder.ivSelectedMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
				}
			}

			UpdateFoot();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView != null) {
				holder = (Holder) convertView.getTag();
				mMapSelectMore.remove(position);
				holder.ivMoreItems.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.local_image_default));
			} else {
				LayoutInflater inflate = LayoutInflater
						.from(StarAppLocalAlbumMultiSelect.this);
				convertView = inflate
						.inflate(R.layout.local_album_recent, null);
				holder = new Holder();
				holder.ivMoreItems = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.ivSelectedMask = (ImageView) convertView
						.findViewById(R.id.iv_selected_mask);
				holder.ivClicked = (ImageView) convertView
						.findViewById(R.id.iv_clicked_to_select);
				holder.ivMoreItems.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.local_image_default));
				convertView.setTag(holder);
			}

			if (null != mListSelectMore && position < mListSelectMore.size()) {
				if (mbDisplay) {
					ImageLoader
							.getInstance()
							.displayImage(
									CommUtil.LOCAL_FILE_PREFIX
											+ mListSelectMore.get(position).mFilePathOrName,
									holder.ivMoreItems, mAvoidOOMOptions, null);
				}

				if (null != mSelectState && position >= 0
						&& mSelectState.length > position) {
					if (mSelectState[position]) {
						holder.ivSelectedMask.setVisibility(View.VISIBLE);
						holder.ivClicked.setVisibility(View.VISIBLE);
					} else {
						holder.ivSelectedMask.setVisibility(View.GONE);
						holder.ivClicked.setVisibility(View.GONE);
					}
				}
			}

			mMapSelectMore.put(position, convertView);

			return convertView;
		}
	}

	/**
	 * 底部已选列表的适配器
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:12:43
	 * 
	 * @version StarAppLocalAlbumMultiSelect
	 * @author HuangYK
	 * 
	 * @see
	 */
	public class FootGridViewAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return mlistSelectedFile.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * item
		 * 
		 * <br>
		 * Created 2014-5-5 下午3:13:25
		 * 
		 * @version StarAppLocalAlbumMultiSelect.FootGridViewAdapter
		 * @author HuangYK
		 * 
		 * @see
		 */
		class Holder {
			ImageView img;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// 最大个数
			final int maxCount = 8;
			Holder holder = null;
			if (null == convertView) {
				convertView = LayoutInflater.from(
						StarAppLocalAlbumMultiSelect.this).inflate(
						R.layout.grid_view_selected, null);
				holder = new Holder();
				holder.img = (ImageView) convertView.findViewById(R.id.iv_img);
				GridView.LayoutParams lp = new GridView.LayoutParams(
						mScreenWidth / maxCount, mScreenWidth / maxCount);
				convertView.setLayoutParams(lp);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			if (position < mlistSelectedFile.size()) {
				ImageLoader
						.getInstance()
						.displayImage(
								CommUtil.LOCAL_FILE_PREFIX
										+ mlistSelectedFile.get(position).mFilePathOrName,
								holder.img, mAvoidOOMOptions, null);
			}

			return convertView;
		}
	}

	@Override
	public void onDestroy() {
		LocalImageController.getInstance().clearLocalMedia();
        mLvLocalAlbum = null;
        m_alAdapter = null;
        if (mListAlbum != null) {
            mListAlbum.clear();
            mListAlbum = null;
        }
        if (mLlHead != null) {
            mLlHead.removeAllViews();
            mLlHead = null;
        }
        mGridViewRecent = null;
        mHeadGridViewAdapter = null;
        if (mListRecent != null) {
            mListRecent.clear();
            mListRecent = null;
        }
        mGvSelectMore = null;
        mSelectMoreGridViewAdapter = null;
        if (mListSelectMore != null) {
            mListSelectMore.clear();
            mListSelectMore = null;
        }
        mRlBottom = null;
        mGvBottom = null;
        mFootGridViewAdatper = null;
        if (mlistSelectedFile != null) {
            mlistSelectedFile.clear();
            mlistSelectedFile = null;
        }
        mBtnFinish = null;
        mPhotoUri = null;
        mCameraFile = null;
        if (mMapRecent != null) {
            mMapRecent.clear();
            mMapRecent = null;
        }
        if (mMapSelectMore != null) {
            mMapSelectMore.clear();
            mMapSelectMore = null;
        }
        mUpdateUI = null;
        mIntentService = null;
        if(mMapAlbumList!=null){
            mMapAlbumList.clear();
            mMapAlbumList = null;
        }
        super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean bFinish = true;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			bFinish = doBackEvent();
			break;
		default:
			break;
		}

		if (bFinish) {
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}

	/**
	 * 回退操作
	 * 
	 * @n<b>函数名称</b> :doBackEvent
	 * @brief
	 * @see
	 * @version Ver 1.1
	 * @param @return
	 * @return boolean
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-4-16下午6:39:06
	 */
	public boolean doBackEvent() {
		mListSelectMore.clear();
		if (View.VISIBLE == mGvSelectMore.getVisibility()) {
			// 从文件夹选择更多中返回
			mLvLocalAlbum.setVisibility(View.VISIBLE);
			mGvSelectMore.setVisibility(View.GONE);

			mHeadGridViewAdapter.initSelectState();
			mHeadGridViewAdapter.notifyDataSetChanged();
			m_alAdapter.setDisplay(true);

			mCommonActivityTitle.setTitleText(R.string.startapp_album);

		} else if (View.GONE == mGvSelectMore.getVisibility()) {
			// 退出本地图片多选
			mlistSelectedFile.clear();
			finish();
			return true;
		}

		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long id) {
		int vid = arg0.getId();
		if (vid == R.id.grid_recent) {
			clickRecent(position);
		} else if (vid == R.id.lvLocalAlbum) {
			clickToSelectMore(position);
		} else if (vid == R.id.gvBottom) {
			disselectFoot(position);
		} else if (vid == R.id.gvSelectMore) {
			if (mIsMultiSelect) {
				mSelectMoreGridViewAdapter.setSelect(position);
			} else {
				FileInfo fileInfo = (FileInfo) mSelectMoreGridViewAdapter
						.getItem(position);
				doSingSelectFinish(fileInfo.mFilePathOrName);
			}
		}
	}

	/**
	 * 点击最近item的操作
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:11:55
	 * 
	 * @param position
	 *            位置
	 * @author : HuangYK
	 */
	private void clickRecent(int position) {
		if (MAX_SELECT_COUNT == mlistSelectedFile.size() && position == 0) {
			// 已经有9张并尝试再选
			ToastUtils.display(StarAppLocalAlbumMultiSelect.this,
					R.string.tweet_upload_images_limit);
			return;
		}
		if (0 == position) {
			// 拍照
			try {
				mCameraFile = new File(getSotrePath());
				mPhotoUri = Uri.fromFile(mCameraFile);

				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

				startActivityForResult(intent, 0);
			} catch (Exception e) {
				Log.v(TAG, e.getMessage());
			}
		} else {
			if (mIsMultiSelect) {
				mHeadGridViewAdapter.setSelect(position);
			} else {
				FileInfo fileInfo = (FileInfo) mHeadGridViewAdapter
						.getItem(position);
				doSingSelectFinish(fileInfo.mFilePathOrName);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			if (mPhotoUri == null) {
				return;
			}
			doCameraResult();
		}
	}
	
	/**
	 * 执行拍照完的处理
	 * 
	 * <br>Created 2014-10-14 下午4:16:59
	 * @author        :  HuangYK
	 */
	private void doCameraResult(){
		try {
			if (mCameraFile != null && mCameraFile.exists()) {
				// 发送广播通知系统更新相册数据库，加入新拍的照片
				Intent intent = new Intent(
						Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
				Uri uri = Uri.fromFile(mCameraFile);
				intent.setData(uri);
				sendBroadcast(intent);

				if (mIsMultiSelect) {
					FileInfo info = new FileInfo();
					info.mFilePathOrName = mCameraFile.getAbsolutePath();
					mlistSelectedFile.add(info);
					doMultiSelectFinish();
				} else {
					doSingSelectFinish(mCameraFile.getAbsolutePath());
				}

			}
		} catch (Exception localException) {
			localException.printStackTrace();
			return;
		}
	}

	/**
	 * 获取相机根目录
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:11:16
	 * 
	 * @return 相机根目录字符串
	 * @author : HuangYK
	 */
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	private String getSotrePath() {
		Time t = new Time();
		t.setToNow();

		String strDir = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/DCIM/Camera/";
		File dir = new File(strDir);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}

		String strPath = strDir + "IMG_" + t.format("%Y%m%d_%H%M%S") + ".jpg";
		return strPath;
	}

	/**
	 * 取消选择
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:11:08
	 * 
	 * @param iPosition
	 *            位置
	 * @author : HuangYK
	 */
	private void disselectFoot(int iPosition) {
		String strRemovePath = mlistSelectedFile.get(iPosition).mFilePathOrName;

		if (View.VISIBLE == mGvSelectMore.getVisibility()) {
			// 文件夹中选择更多时，要把被选中的反选
			for (int i = 0; i < mListSelectMore.size(); i++) {
				if (mListSelectMore.get(i).mFilePathOrName
						.equalsIgnoreCase(strRemovePath)) {
					mSelectMoreGridViewAdapter.setSelect(i);
					return;
				}
			}
		} else if (View.GONE == mGvSelectMore.getVisibility()) {
			// 文件夹列表中，要把头部中被选中的反选
			for (int i = 1; i < mListRecent.size(); i++) {
				if (mListRecent.get(i).mFilePathOrName
						.equalsIgnoreCase(strRemovePath)) {
					mHeadGridViewAdapter.setSelect(i);
					return;
				}
			}
		}

		// 没找到，直接remove
		mlistSelectedFile.remove(iPosition);
		UpdateFoot();
	}

	/**
	 * 点击查看更多
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:10:31
	 * 
	 * @param iPos
	 *            位置
	 * @author : HuangYK
	 */
	private void clickToSelectMore(int iPos) {
		int iSize = mListAlbum.size() + 1; // 因为加了头部
		if (iPos < 0 || iPos + 1 > iSize) {
			return;
		}

		SortedMediaFiles smf = mListAlbum.get(iPos - 1);
		if (null == smf) {
			return;
		}

		mCommonActivityTitle.setTitleText(smf.getDirName());

		mLvLocalAlbum.setVisibility(View.GONE);
		mGvSelectMore.setVisibility(View.VISIBLE);

		mListSelectMore.clear();
		List<FileInfo> listFI = smf.getFilesList();
		if (null != listFI) {
			for (FileInfo fi : listFI) {
				mListSelectMore.add(fi);
			}
		}

		mSelectMoreGridViewAdapter.initSelectState();
		mSelectMoreGridViewAdapter.setDisplay(true);
		mSelectMoreGridViewAdapter.notifyDataSetChanged();
	}

	private OnScrollListener scrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// if (0 == scrollState) {
			// if (View.VISIBLE == mLayoutSelectMore.getVisibility()) {
			// mSelectMoreGridViewAdapter.setDisplay(true);
			// mSelectMoreGridViewAdapter.notifyDataSetChanged();
			// } else if (View.GONE == mLayoutSelectMore.getVisibility()) {
			// m_alAdapter.setDisplay(true);
			// m_alAdapter.notifyDataSetChanged();
			// }
			// } else {
			// m_alAdapter.setDisplay(false);
			// mSelectMoreGridViewAdapter.setDisplay(false);
			// }
		}
	};

	/**
	 * 取数据库失败时，启服务去搜两层
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:09:47
	 * 
	 * @author : HuangYK
	 */
	private void startServiceToSearch() {
		boolean bSDCardExist = android.os.Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);
		if (bSDCardExist) {
			if (isServiceRunning(this, ImageSearchService.class.getName())) {
				// 不做处理
				return;
			} else if (null == mIntentService) {
				mIntentService = new Intent(this, ImageSearchService.class);
				startService(mIntentService);
			} else {
				startService(mIntentService);
			}
		} else {
			Toast.makeText(this, R.string.no_sd_card, Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 开始
	 * 
	 * <br>
	 * Created 2014-6-9 下午6:06:45
	 * 
	 * @author : HuangYK
	 */
	protected void onStart() {
		ProgressTask task = new ProgressTask(this, R.string.loading) {
			// 取得文件的文件夹路径
			public String getImageDirName(String strPath) {
				int iPos = strPath.lastIndexOf('/');
				return strPath.substring(0, iPos + 1);
			}

			@Override
			protected void doSuccess() {
				LocalImageController.getInstance().notifyObservers();
			}

			@Override
			protected void doFail(int result) {
				startServiceToSearch();
			}

			@Override
			protected Integer doInBackground(Void... arg0) {
				Cursor cursor = null;
				try {
					mMapAlbumList.clear();
					String[] projection = new String[] {
							MediaStore.Images.ImageColumns._ID,
							MediaStore.Images.ImageColumns.DATA,
							MediaStore.Images.ImageColumns.DATE_TAKEN };

					ContentResolver cr = getContentResolver();
					cursor = cr.query(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							projection, null, null, null);
					if (null != cursor) {
						while (cursor.moveToNext()) {
							long lID = cursor
									.getLong(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns._ID));
							String strImagePath = cursor
									.getString(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
							long lDateTaken = cursor
									.getLong(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN));
							
							if(!new File(strImagePath).exists()){
								continue;
							}

							String strImageDir = getImageDirName(strImagePath);
							String strImageExt = StarAppUtils
									.getExtFromFilename(strImagePath);
							if (TextUtils.isEmpty(strImageExt)) {
								continue;
							}
							if (!StarAppUtils.judgeExtensionIsValid(
									strImageExt, mIsUsedGif)) {
								continue;
							}

							if (!mMapAlbumList.containsKey(strImageDir)) {
								// 无此文件夹则创建
								File dir = new File(strImageDir);
								if (!dir.isDirectory()
										|| -1 != strImageDir.indexOf("/.")) {
									continue;
								}

								FileInfo dirInfo = new FileInfo();
								dirInfo.mFilePathOrName = dir.getAbsolutePath();

								SortedMediaFiles smf = new SortedMediaFiles();
								smf.mDirInfo = dirInfo;

								mMapAlbumList.put(strImageDir, smf);
							}

							SortedMediaFiles smf = mMapAlbumList
									.get(strImageDir);
							if (null != smf) {
								FileInfo fi = new FileInfo();
								fi.mFilePathOrName = strImagePath;
								fi.mLastModified = lDateTaken;
								fi.mID = lID;

								// 更新最后更新时间
								smf.mDirInfo.mLastModified = Math.max(
										lDateTaken, smf.mDirInfo.mLastModified);

								smf.addFile(fi);
							}
						}
					}

					LocalImageController.getInstance().clearLocalMedia();
					Iterator<?> iter = mMapAlbumList.entrySet().iterator();
					while (iter.hasNext()) {
						@SuppressWarnings("rawtypes")
						Map.Entry entry = (Map.Entry) iter.next();
						LocalImageController.getInstance().addMediaFile(
								(SortedMediaFiles) entry.getValue());
					}
					return 0;
				} catch (Exception e) {
					return 1;
				} finally {
					if (cursor != null) {
						cursor.close();
					}
				}
			}
		};
		task.execute();
		super.onStart();
	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:08:38
	 * 
	 * @param mContext
	 *            上下文
	 * @param className
	 *            服务名
	 * @return boolean
	 * @author : HuangYK
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		final int maxNum = 30;
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(maxNum);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className)) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	/**
	 * 将选中的图片移除
	 * 
	 * <br>
	 * Created 2014-5-5 下午3:09:11
	 * 
	 * @param strPath
	 *            路径
	 * @author : HuangYK
	 */
	private void removeSeletedImg(String strPath) {
		for (FileInfo info : mlistSelectedFile) {
			if (0 == info.mFilePathOrName.compareToIgnoreCase(strPath)) {
				mlistSelectedFile.remove(info);
				return;
			}
		}
	}

	/**
	 * Title按钮点击事件监听
	 */
	private TitleBtnCallback mTitleBtnCallback = new TitleBtnCallback() {

		@Override
		public void onBtnClick(int clickType) {
			doBackEvent();
		}
	};
}